/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wephone.Student.huanxin.adapter;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.easemob.chat.EMChatDB;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContact;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.DateUtils;
import com.easemob.util.EasyUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.wephone.Student.R;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.db.InviteMessgeDao;
import com.wephone.Student.huanxin.domain.InviteMessage;
import com.wephone.Student.huanxin.domain.InviteMessage.InviteMesageStatus;
import com.wephone.Student.huanxin.utils.SmileUtils;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.ImageLoaderUtil;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.huanxin.domain.User;

/**
 * 聊天记录adpater
 * 
 */
public class ChatHistoryAdapter extends ArrayAdapter<EMContact> {
	private Context context;
	private LayoutInflater inflater;
	private List<UserInfoData> userInfoList;
	private List<GroupInfo> groupInfoList;

	public ChatHistoryAdapter(List<UserInfoData> userInfoList,List<GroupInfo> groupInfoList,Context context, int textViewResourceId, List<EMContact> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.userInfoList = userInfoList;
		this.groupInfoList = groupInfoList;
		inflater = LayoutInflater.from(context);
	}
	
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.default_user_logo)
    .showImageOnFail(R.drawable.default_user_logo)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(1000))
    .build();

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.row_chat_history, parent, false);
		}
		ViewHolder holder = (ViewHolder) convertView.getTag();
		if (holder == null) {
			holder = new ViewHolder();
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number);
			holder.message = (TextView) convertView.findViewById(R.id.message);
			holder.time = (TextView) convertView.findViewById(R.id.time);
			holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
			holder.msgState = convertView.findViewById(R.id.msg_state);
			holder.list_item_layout=(RelativeLayout) convertView.findViewById(R.id.list_item_layout);
			convertView.setTag(holder);
		}
		if(position%2==0){
			holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem);
		}else{
			holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem_grey);
		}
		
		
		EMContact user = getItem(position);
		if(user instanceof EMGroup){
			//群聊消息，显示群聊头像
			//holder.avatar.setImageResource(R.drawable.group_icon);
			String gId = ((EMGroup) user).getGroupId();
			
			for(GroupInfo userInfo:groupInfoList){
				if(gId.equals(userInfo.getGroupid())){
//					ImageLoaderUtil.getInstance(context, R.drawable.default_avatar).displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userInfo.getuIcon(), holder.avatar,options);
					ImageLoaderUtil.getInstance(context, R.drawable.group_icon).displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userInfo.getPic(), holder.avatar, options);
					break;
				}
			}
		}else if(user.getUsername() == Constant.NEW_FRIENDS_USERNAME)
		{
			holder.avatar.setImageResource(R.drawable.group_icon);
			holder.name.setText(user.getNick());
			int num = ((User)user).getUnreadMsgCount();
			if(num>0){
				holder.unreadLabel.setText(String.valueOf(num));
				holder.unreadLabel.setVisibility(View.VISIBLE);
			}else{
				holder.unreadLabel.setVisibility(View.GONE);
			}
			holder.message.setVisibility(View.GONE);
			
			holder.time.setVisibility(View.GONE);
			holder.msgState.setVisibility(View.GONE);
			/*
			InviteMessgeDao dao = new InviteMessgeDao(context);
			List<InviteMessage> msgs = dao.getMessagesList();
			if(msgs.size()>0){
				InviteMessage msgInviteMessage = msgs.get(0);
				holder.name.setText(user.getNick());
				//holder.name.setTextColor(context.getResources().getColor(R.color.default_black))
				int num=0;
				for(int i=0;i<msgs.size();i++){
					if(msgs.get(i).getStatus()==InviteMesageStatus.BEAPPLYED){
						num++;
					}
				}
				if(num>0){
					holder.unreadLabel.setText(String.valueOf(num));
					holder.unreadLabel.setVisibility(View.VISIBLE);
				}else{
					holder.unreadLabel.setVisibility(View.GONE);
				}
				String pushUserStr = ShareReferenceUtil
						.getPushUserInfoJson(context);
				Gson gson = new Gson();
				List<UserInfoData> userInfoList = gson.fromJson(pushUserStr,
								new TypeToken<List<UserInfoData>>() {
								}.getType());
				UserInfoData nowFrom = new UserInfoData();
				for(UserInfoData userInfo:userInfoList){
					if(msgInviteMessage.getFrom().equals(userInfo.getuId())){
						nowFrom = userInfo;
						break;
					}
				}
				if(nowFrom.getuName()!=null){
					holder.message.setText(nowFrom.getuName()+" 申请加入群 "+msgInviteMessage.getGroupName());
				}else{
					holder.message.setText(msgInviteMessage.getFrom()+" 申请加入群 "+msgInviteMessage.getGroupName());
				}
				
				holder.time.setText(DateUtils.getTimestampString(new Date(msgInviteMessage.getTime())));
				holder.msgState.setVisibility(View.GONE);
				
			}else{
				holder.unreadLabel.setVisibility(View.GONE);
			}*/
			ImageLoaderUtil.getInstance(context, R.drawable.group_icon).displayImage("http://www.baidu.com", holder.avatar, options);
			return convertView;
		}
		else{
//			holder.avatar.setImageResource(R.drawable.default_avatar);
			//TODO
			String userId = user.getUsername();
			if(userId.equals("admin")){
				userId = "5519";
			}
			for(UserInfoData userInfo:userInfoList){
				if(userId.equals(userInfo.getuId())){
//					ImageLoaderUtil.getInstance(context, R.drawable.default_avatar).displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userInfo.getuIcon(), holder.avatar,options);
					String endStr = userInfo.getuIcon().substring(userInfo.getuIcon().lastIndexOf("."));
					ImageLoaderUtil.getInstance(context, R.drawable.default_avatar).displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userInfo.getuIcon().replace(endStr, "_150_150"+endStr), holder.avatar, options);
					break;
				}
			}
		}
		
		String username = user.getUsername();
		
		// 获取与此用户/群组的会话
		EMConversation conversation = EMChatManager.getInstance().getConversation(username);
		holder.name.setText(user.getNick() != null ? user.getNick() : username);
		if (conversation.getUnreadMsgCount() > 0) {
			// 显示与此用户的消息未读数
			holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
			holder.unreadLabel.setVisibility(View.VISIBLE);
		} else {
			holder.unreadLabel.setVisibility(View.INVISIBLE);
		}

		if (conversation.getMsgCount() != 0) {
			// 把最后一条消息的内容作为item的message内容
			EMMessage lastMessage = conversation.getLastMessage();
			holder.message.setText(SmileUtils.getSmiledText(getContext(), getMessageDigest(lastMessage, (this.getContext()))),
					BufferType.SPANNABLE);

			holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
			if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) {
				holder.msgState.setVisibility(View.VISIBLE);
			} else {
				holder.msgState.setVisibility(View.GONE);
			}
		}
			

		return convertView;
	}

	/**
	 * 根据消息内容和消息类型获取消息内容提示
	 * 
	 * @param message
	 * @param context
	 * @return
	 */
	private String getMessageDigest(EMMessage message, Context context) {
		String digest = "";
		switch (message.getType()) {
		case LOCATION: // 位置消息
			if (message.direct == EMMessage.Direct.RECEIVE) {
				digest = EasyUtils.getAppResourceString(context, "location_recv");
				digest = String.format(digest, message.getFrom());
				return digest;
			} else {
				digest = EasyUtils.getAppResourceString(context, "location_prefix");
			}
			break;
		case IMAGE: // 图片消息
			ImageMessageBody imageBody = (ImageMessageBody) message.getBody();
			digest = EasyUtils.getAppResourceString(context, "picture") + imageBody.getFileName();
			break;
		case VOICE:// 语音消息
			digest = EasyUtils.getAppResourceString(context, "voice");
			break;
		case VIDEO: // 视频消息
			digest = EasyUtils.getAppResourceString(context, "video");
			break;
		case TXT: // 文本消息
			TextMessageBody txtBody = (TextMessageBody) message.getBody();
			digest = txtBody.getMessage();
			break;
		default:
			System.err.println("error, unknow type");
			return "";
		}

		return digest;
	}

	private static class ViewHolder {
		/** 和谁的聊天记录 */
		TextView name;
		/** 消息未读数 */
		TextView unreadLabel;
		/** 最后一条消息的内容 */
		TextView message;
		/** 最后一条消息的时间 */
		TextView time;
		/** 用户头像 */
		ImageView avatar;
		/** 最后一条消息的发送状态 */
		View msgState;
		/**整个list中每一行总布局*/
		RelativeLayout list_item_layout;
		
		
	}
}
